package cn.sise.edu.crm.web.controller;

import cn.sise.edu.crm.domain.*;
import cn.sise.edu.crm.query.BuyRecordQueryObject;
import cn.sise.edu.crm.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by chen on 2019/11/3.
 */
@Controller
@RequestMapping("/buyRecord")
public class BuyRecordController {
    @Autowired
    private IBuyRecordService buyRecordService;
    @Autowired
    private ISystemDictionaryItemService systemDictionaryItemService;
    @Autowired
    private ICustomerService customerService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") BuyRecordQueryObject qo) {

        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        if(!(subject.hasRole("李四")||subject.hasRole("Market_Manager"))){
            qo.setSellerId(employee.getId());//查询所有负责的客户
        }
        PageInfo<BuyRecord> pageInfo = buyRecordService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("qo", qo);
        List<Customer> customers = customerService.selectAll();
        List<SystemDictionaryItem> courses = systemDictionaryItemService.queryBySystemDictionarySn("course");
        model.addAttribute("customers",customers);
        model.addAttribute("courses", courses);
        return "buyRecord/list";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(BuyRecord buyRecord) {
        try {
            buyRecord.setInputTime(new Date());
            buyRecordService.insert(buyRecord);
            Customer customer = customerService.selectById(buyRecord.getCustomer().getId());
            customer.setStatus(1);
            customerService.update(customer);
        }catch (Exception e){
            return new JsonResult("保存或者更新失败",false);
        }

        return  new JsonResult("保存或者更新成功",true);
    }
}
